package cloud.seata.account.controller;


import cloud.seata.account.repository.AccountRepository;
import cloud.seata.account.repository.entity.Account;
import cloud.seata.account.tcc.TccAccountAction;
import org.apache.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

@RestController
@Transactional
public class AccountController implements TccAccountAction {

    @Autowired
    private AccountRepository accountRepository;


    @Override
    public ResponseEntity<Boolean> prepare(@RequestBody BusinessActionContext actionContext) {

        Account account = accountRepository.selectById(1);


        Account a = new Account();

        a.setId(1);
        a.setWallet(account.getWallet().subtract(BigDecimal.valueOf(500)));
        a.setFrozen(account.getFrozen().add(BigDecimal.valueOf(500)));
        accountRepository.updateById(a);

        return ResponseEntity.status(HttpStatus.OK).body(Boolean.TRUE);
    }


    @Override
    public boolean commit(@RequestBody BusinessActionContext actionContext) {


        Account account = accountRepository.selectById(1);


        account.setFrozen(account.getFrozen().subtract(BigDecimal.valueOf(500)));
        accountRepository.updateById(account);

        return true;
    }

    @Override
    public boolean rollback(@RequestBody BusinessActionContext actionContext) {

        Account account = accountRepository.selectById(1);

        account.setFrozen(account.getFrozen().subtract(BigDecimal.valueOf(500)));
        account.setWallet(BigDecimal.valueOf(500));
        return true;
    }
}
